import re
import time
import urllib

from selenium import webdriver
import requests
from bs4 import BeautifulSoup
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
import os

# PROXY_POOL_URL = 'http://localhost:5555/random'
#
#
# def get_proxy():
#     try:
#         response = requests.get(PROXY_POOL_URL)
#         if response.status_code == 200:
#             return response.text
#     except ConnectionError:
#         return None
#
#
# proxie = {
#     'http': get_proxy()
# }

chrome_options = Options()
prefs = {
    "profile.default_content_setting_values.plugins": 1,
    "profile.content_settings.plugin_whitelist.adobe-flash-player": 1,
    "profile.content_settings.exceptions.plugins.*,*.per_resource.adobe-flash-player": 1,
}
# chrome_options.add_argument('--headless')
chrome_options.add_experimental_option("prefs", prefs)
chrome_options.add_argument("--remote-debugging-port=9225");
# chrome_options.add_argument("--mute-audio")
# chrome_options.add_argument('--disable-gpu')
# chrome_options.add_argument('--proxy-server=%s' % get_proxy())
driver = webdriver.Chrome(options=chrome_options)

dir = r'TFH_Annotated_Dataset'
find_txt = re.compile(r'[0-9a-zA-Z]+\.txt')
txt_dir = ','.join(os.listdir(dir))
txts = find_txt.findall(txt_dir)
# find_ann = re.compile(r'[0-9a-zA-Z]+\.ann')
# ann_dir = ','.join(os.listdir(dir))
# anns = find_ann.findall(ann_dir)



driver.get('https://www.deepl.com/translator')
driver.find_elements_by_class_name('lmt__language_select__active')[1].click()
driver.find_element_by_class_name('lmt__language_select__menu').find_elements_by_tag_name('button')[1].click()
driver.find_element_by_css_selector('.lmt__textarea.lmt__source_textarea.lmt__textarea_base_style').clear()
driver.find_element_by_css_selector('.lmt__textarea.lmt__source_textarea.lmt__textarea_base_style').send_keys("Now!!!!")
time.sleep(5)

for txt in txts:
    ann = txt.replace('.txt','.ann')
    print(ann)
    texts = ''
    with open(dir + '\\' + ann, 'r', encoding='utf-8') as f:
        position = []
        for line in f.readlines():
            trans = ''
            late = ''
            entity = re.split('[\t, ,\n]',line,maxsplit=4)
            entity[4] = entity[4].rstrip('\n')
            if entity[0].__contains__('T'):
                # position.append([entity[4],entity[2],entity[3]])
                driver.find_element_by_css_selector(
                    '.lmt__textarea.lmt__source_textarea.lmt__textarea_base_style').clear()
                driver.find_element_by_css_selector(
                    '.lmt__textarea.lmt__source_textarea.lmt__textarea_base_style').send_keys(entity[4])
                time.sleep(5)
                word = driver.find_element_by_id('target-dummydiv').get_attribute("textContent").rstrip('\n')
                driver.find_element_by_css_selector(
                    '.lmt__textarea.lmt__source_textarea.lmt__textarea_base_style').clear()
                driver.find_element_by_css_selector(
                    '.lmt__textarea.lmt__source_textarea.lmt__textarea_base_style').send_keys(entity[1])
                type = driver.find_element_by_id('target-dummydiv').get_attribute("textContent").rstrip('\n')
                position.append([type, word, entity[4]])
        f.close()
    with open(dir + '\\' + txt, 'r', encoding='utf-8') as f:
        text = f.read()
        for p in position:
            # text = text[:p[2]]+p[1]+text[p[3]+1:]
            text = text.replace(p[2],p[1])
        # print(text)

        driver.find_element_by_css_selector('.lmt__textarea.lmt__source_textarea.lmt__textarea_base_style').clear()
        driver.find_element_by_css_selector('.lmt__textarea.lmt__source_textarea.lmt__textarea_base_style').send_keys(text)
        time.sleep(3)
        driver.find_elements_by_class_name('lmt__language_select__active')[0].click()
        driver.find_element_by_class_name('lmt__language_select__menu').find_elements_by_tag_name('button')[6].click()
        f.close()
    time.sleep(3)
    parts = driver.find_element_by_id('target-dummydiv').get_attribute("textContent")
    print(parts)
    break
    # for part in parts:
    #     contents = part.text.split()
    #     for content in contents:
    #         for con in list(content):
    #             texts = texts + con + ' O\n'
    #         texts = texts + '\n'
    # with open(r'C:\Users\Geralt\PycharmProjects\crawler\translated\all.txt','a',encoding='utf-8') as g:
    #     g.write(texts)
    # # driver.implicitly_wait(3)
    # print(txt)
    # print(texts)